package com.kaifamiao.listener;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.logging.Logger;

public class SessionLifecycleServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void doGet( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        String uri = request.getRequestURI();
        logger.info( "uri = " + uri );
        int last = uri.lastIndexOf( "/" ) ;
        String operation = uri.substring( last + 1 );
        logger.info( "operation = " + operation );

        HttpSession session ;
        switch ( operation.toLowerCase() ){
            case "create" :
                // 获得与当前请求关联的会话对象 ( 若已存在则直接返回，否则创建新的 )
                session = request.getSession();
                logger.info( "session is new : " + session.isNew() );
                break;
            case "destroy" :
                // 获得与当前请求关联的会话对象 ( 参数 false 表示若不存在会话对象则不要创建新的 )
                session = request.getSession( false );
                if( session != null ) {
                    logger.info("session destroy : " + session);
                    // 废弃整个会话对象
                    session.invalidate();
                }
                break;
        }

        response.sendRedirect( request.getContextPath() + "/index.jsp" );
    }
}
